package com.example.fw;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JDialog;
import javax.swing.tree.TreePath;

import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JTreeOperator;

import com.example.tests.Folders;

public class FolderHelper extends HelpersBase{
	
	private static Random randomizer = new Random();
	public static String generateRandomFolderName(){
		return "newfolder" + String.format("%05X", randomizer.nextLong()); 
	}
	

	public FolderHelper(ApplicationManager applicationManager) {
		super(applicationManager);
	}

	public Folders getFolders() {
		List<String> list = new ArrayList<String>();
		JTreeOperator tree = new JTreeOperator(mainFrameOperator);
		Object[] children = tree.getChildren(tree.getRoot());
		for(Object child : children){
			list.add("" + child);
		}
		return new Folders(list);
	}
	
	public void deleteFolder(final String foolderName){
		JTreeOperator tree = new JTreeOperator(mainFrameOperator);
		tree.clickOnPath(tree.findPath(new JTreeOperator.TreePathChooser(){

			@Override
			public boolean checkPath(TreePath path, int index) {
				System.err.println(path.toString());
				return path.toString().contains(foolderName);
			}

			@Override
			public String getDescription() {
				return null;
			}

			@Override
			public boolean hasAsParent(TreePath path, int index) {
				return false;
			}
			
		}));
		//new TreePath(new Object[] {"jAddressBook",foolderName})
		manager.getMenuHelper().pushDeleteFolder();
		JDialogOperator dialog = new JDialogOperator(mainFrameOperator);
		new JButtonOperator(dialog, "YES").push();
	}

	public String createFolder(String folderName) {
		manager.getMenuHelper().pushCreateFolder();
		JDialogOperator dialog = new JDialogOperator(mainFrameOperator);
		new JTextFieldOperator(dialog).setText(folderName);
		new JButtonOperator(dialog, "OK").push();
		
		return whaitMessageDialog("Warning", 3000);
	}

	private String whaitMessageDialog(String title, int timeout) {
		long start = System.currentTimeMillis();
		
		long currentTime = start;
		while(currentTime < start + timeout){ 
			JDialog dialog = JDialogOperator.findJDialog(mainFrameOperator.getOwner(), title, false, false);
			if(dialog != null){
				JDialogOperator dialogOp = new JDialogOperator(dialog);
				String message = new JLabelOperator(dialogOp).getText();
				dialogOp.requestClose();
				return message;
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			currentTime = System.currentTimeMillis();
		}
		return null;
	}

	
}
